import { ElMessage } from "element-plus";
import getFile from "@/utils/getFile";
import { getConfig, followUp, stsMsg } from "@/api/modules/upload";
import { Upload } from "@/api/interface/upload";
import { StStore } from "@/stores/modules/sts";
import { ref , computed , watch} from "vue";
import OSS from "ali-oss";
type FileLists = { file_name: string; file_type: string; size: number, sizeText: string, file: File, dir_id: number | string, is_common: 1 | 0 };
function init(uploadSuccFunc: undefined | (() => void) = undefined) {
	const stStore = StStore();

	const client = ref<OSS | undefined>(undefined);

	const fileLists = ref<Array<{ fileList: FileList, dir_id: string | number ,is_common:1|0}>>([]);

	const percentageArr = ref<number[]>([]);

	watch(() => fileLists.value.length,()=>{
		processTasks().start();
	});

	stStore.loadConfig((oss_config) => {
		if (oss_config) {
			client.value = new OSS({
				// yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
				region: 'oss-cn-guangzhou',
				// 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
				accessKeyId: oss_config.accessKeyId,
				accessKeySecret: oss_config.accessKeySecret,
				// 从STS服务获取的安全令牌（SecurityToken）。
				stsToken: oss_config.securityToken,
				// 填写Bucket名称。
				bucket: oss_config.oss_bucket
			});

			// console.log(client.value);
		}
	});
	const upload = (is_common: 1 | 0, dir_id: string | number , selAfterFunc : undefined | (()=>void)  = undefined) => {
		getFile(
			(file: File) => {
				if (stStore.uploadConfigGet === undefined) return false;
				else if (stStore.uploadConfigGet.upload_check_file_type === 0) return true;
				else {
					console.log(file);
					const [type] = file.type.split("/");
					if (!type) throw `暂不支持${file.name}的文件类型上传`;
					else if (!stStore.uploadConfigGet.upload_file_type) throw "上传文件失败";
					else if (stStore.uploadConfigGet.upload_file_type.findIndex((item) => item.type === type) === -1) throw `暂不支持${file.name}的文件类型上传`;
				}
				return true;
			},
			stStore.uploadConfigGet?.upload_max_size,
			{
				successResult: async (fileList: FileList) => {
					// console.log(fileList);
					// let sizes:number = files.size;
					// let dir_id:number = dir_id;
					// console.log(fileList.map);
					// const file_type = ;
					// let fileArr: Array<Upload.File.FileLists> = [];
					// for (let i = 0; i < fileList.length; i++) {
					// 	fileArr.push({
					// 		file_name: fileList[i].name,
					// 		file_type: fileList[i].type.split("/")[0],
					// 		size: fileList[i].size
					// 	});
					// }

					if (selAfterFunc) selAfterFunc();
					fileLists.value.push({ fileList: fileList, is_common, dir_id });


					










					// fileFirst({ dir_id, is_common: is_common, file_list: fileArr }).then(async res => {
					// 	// res.data.file_list;
					// 	await followUp({ file: fileList[0], oid: res.data.file_list[0].oid });
					// });
					// for(let i=0;i<files.length;i++){
					// }
					// switch(fileType){
					// 	// 图片类型
					// 	case 'png':
					// 	case 'jpg':
					// 	case 'jpeg':
					//   mittBus.emit('loadImageFromFile',file);
					//   // mittBus.emit('loadImageFromURL',"https://vimsky.com/wp-content/uploads/2020/02/abb4138bfaf63fd24a35666bfe440605.jpg");
					// 	break;
					// }
				},
				errorResult: (msg: string) => {
					ElMessage.error(msg);
				}
			},
			true
		);
	};

	const uploadList = computed(()=>{

		let fileArr: FileLists[] = [];

				fileLists.value.forEach((item)=>{
					 for(let i=0;i<item.fileList.length;i++){
						 fileArr.push({
							 file_name: item.fileList[i].name,
							 file_type: item.fileList[i].type.split("/")[0],
							 size: item.fileList[i].size,
							 file: item.fileList[i],
							 dir_id:item.dir_id,
							 is_common:item.is_common,
							 sizeText: fileUnit(item.fileList[i].size)
						 });
					 }
				});

	
		return fileArr;
	});

	const fileUnit = (size:number)=>{
		if (size >= 1024 * 1024 * 1024) return Math.floor(size / 1024 / 1024 / 1024) + 'GB';
	  else	if ( size >= 1024 * 1024 ){
			return Math.floor(size / 1024 / 1024) + 'MB';
		}else return Math.floor(size / 1024) + 'KB';
	}

	const isRunning = ref<boolean>(false);

	const startIndex = ref<number>(0);





  
  function processTasks(){
    
		return {

			 start:async ()=>{
				if (isRunning.value) return;

				isRunning.value = true;

				while (startIndex.value <= uploadList.value.length - 1){
					await sliceUpload(
						uploadList.value[startIndex.value].file, 
						uploadList.value[startIndex.value].dir_id, 
						uploadList.value[startIndex.value].is_common
					);
					 startIndex.value++;
				}

				isRunning.value = false;

			 }


		}
		  

	}


	const upload_slice_size = computed(()=>{
		return (stStore.uploadConfigGet?.upload_slice_size ? stStore.uploadConfigGet?.upload_slice_size : 1024) * 1024;
	});

	const createOption = ()=>{
		return {
			// meta: { temp: "demo" },
			mime: "json",
			headers: { "Content-Type": "text/plain" },
		};
	}


	function sliceUpload(file:File,dir_id:number|string,is_common:1|0){
 
		return new Promise((resolve, reject)=>{
			if (client.value) {

				try {
					// 填写Object完整路径。Object完整路径中不能包含Bucket名称。
					// 您可以通过自定义文件名（例如exampleobject.txt）或文件完整路径（例如exampledir/exampleobject.txt）的形式实现将数据上传到当前Bucket或Bucket中的指定目录。
					// data对象可以自定义为file对象、Blob数据或者OSS Buffer。
					// const options = createOption();


					// console.log(fileList[0]);


					// let upload_slice_size = 



					// let { uuid } = (await stsMsg({ num: fileArr.length })).data;

					// console.log(uuid, 'uuid');

					// for (let i = 0; i < fileList.length; i++) {

					let suffix = file.name.includes('.') ?  file.name.split('.').at(-1) : '';

						let options = {
							// 获取分片上传进度、断点和返回值。
							progress: (p: any, cpt: any, res: any) => {

								percentageArr.value[startIndex.value] = p;
								if (p === 1){
									console.log('test');
									resolve(true);
									if (uploadSuccFunc)	uploadSuccFunc();
								} 
								// console.log(p, 'p');
								// console.log(cpt, 'cpt');
								// console.log(res, 'res');
							},
							// 设置并发上传的分片数量。
							parallel: Math.ceil(file.size / upload_slice_size.value),
							// 设置分片大小。默认值为1 MB，最小值为100 KB。
							partSize: upload_slice_size.value,
							// headers,
							// 自定义元数据，通过HeadObject接口可以获取Object的元数据。
							// meta: {  uuid  },
							mime: "text/plain",
						};


					client.value.multipartUpload(stStore.createOssUrl( (Math.floor(Math.random() * 100)).toString() , dir_id.toString(), is_common, suffix ? suffix : ''),  file , {
							...options,
							// 设置上传回调。
							// 如果不涉及回调服务器，请删除callback相关设置。
						}).then((res: any) => {
							console.log(res, 'res');
						});

					// 	// console.log(res,'res');
					// }



					// const result = await client.value.put( stStore.createOssUrl(nanoid, dir_id.toString(), is_common , fileList[0].type.split("/")[0]) , fileList[0], options);

					// console.log(result);

				} catch (e) {
					reject(e);
				}
			}

		});


		
		  

	}



	return { upload, uploadList, percentageArr };
}

export default init;

